package com.itboye.ihomebank.activity.key;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.itboye.ihomebank.KeyFragment;
import com.itboye.ihomebank.MainActivity;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.guanjia.ActivityGuanJia;
import com.itboye.ihomebank.activity.keytwo.KeyGuanLiActivity;
import com.itboye.ihomebank.activity.keytwo.RentingOrderListActivity;
import com.itboye.ihomebank.activity.login.LoginActivity;
import com.itboye.ihomebank.activity.qianyue.ActivityMySign;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.KeysBean;
import com.itboye.ihomebank.bean.RedDotBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.interfaces.IRefreshAfterAlert;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.ttKey.BleConstant;
import com.itboye.ihomebank.ttKey.BleSession;
import com.itboye.ihomebank.ttKey.DaoMaster;
import com.itboye.ihomebank.ttKey.DaoSession;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.KeyDao;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.ttKey.Operation;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.ListDialog;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SaveKeyBean;
import com.itboye.ihomebank.util.TimesUtils;
import com.ttlock.bl.sdk.api.TTLockAPI;
import com.ttlock.bl.sdk.callback.TTLockCallback;
import com.ttlock.bl.sdk.entity.Error;
import com.ttlock.bl.sdk.scanner.ExtendedBluetoothDevice;
import com.ttlock.bl.sdk.util.DigitUtil;
import com.ttlock.bl.sdk.util.LogUtil;

import org.greenrobot.greendao.database.Database;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;


import static com.itboye.ihomebank.KeyFragment.curKeys;

import static com.itboye.ihomebank.base.MyApplcation.curActivity;
import static com.itboye.ihomebank.base.MyApplcation.getStringContent;
import static com.itboye.ihomebank.ttKey.Operation.UNLOCK;
import static com.itboye.ihomebank.util.SPUtils.get;
import static com.ttlock.bl.sdk.util.GsonUtil.gson;
import static java.lang.Long.parseLong;
import static java.lang.System.currentTimeMillis;

/**
 * 管理员用户（锁）
 */
public class ActivityGuanLiKey extends BaseOtherActivity implements Observer {
    View v_statusbar;
    ImageView key_finish;// 返回
    TextView key_title;// 标题
    ImageView key_shezhi;// 设置
    ImageButton icon;// 开锁
    ToggleButton key_tb;//开锁声音
    String key_play = "";
    String cy_mac;
    KeyFragment mKeyFragment;
    private LinearLayout bottom, bottom3;
    private TextView key_send;//发送密码的text
    TextView shijain_start, shijain_end;//开始时间，结束时间

    // 发送钥匙，发送密码，用户管理，开锁记录
    LinearLayout key_send_yaoshi, key_send_pass, key_guanli, key_jilu;
    public static Key localKey;

    private RelativeLayout icRl;
    PopupWindow popupWindow;

    private List<KeysBean> kensBean;//钥匙列表数据
    private List<Key> keys;//本地缓存的钥匙
    public static DaoSession daoSession;
    public static KeyDao keyDao;

    TextView key_tv_mess, key_tv_jiaozu, key_tv_weixiu, key_tv_zhangdan;//消息，交租，维修，账单
    ImageView key_img_mess, key_img_jiaozu, key_img_weixiu, key_img_zhangdan;//消息，交租，维修，账单消息 红点显示

    public static String activity //是从哪条转过来的，钥匙界面，还是从主界面跳转过来的常用锁
            ,leixing;
    private String uid;
    int activityType=0;//2 是否是从闪屏页调转过来的   其他

    HousePresenter mHousePresenter;
    KeyPresenter keyPresenter;
    public static String device_token;
    ListDialog mShenQin,mQianDing,mFujian,mYuQi;
    Timer timer;

    private static boolean DBG = true;
    private boolean operateSuccess = true;
    private UserPresenter userPresenter;
    private String lockid;
    public static TTLockAPI mTTLockAPI;
    private Context mContext;
    public  int diconectNum=0;
    public static BleSession bleSession = BleSession.getInstance(UNLOCK, null);
    private boolean isLock;
    private String sid;
    /**
     * 按下这个按钮进行的颜色过滤
     */
    public final static float[] BT_SELECTED = new float[]{
            2, 0, 0, 0, 2,
            0, 2, 0, 0, 2,
            0, 0, 2, 0, 2,
            0, 0, 0, 1, 0};

    /**
     * 按钮恢复原状的颜色过滤
     */
    public final static float[] BT_NOT_SELECTED = new float[]{
            1, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 1, 0, 0,
            0, 0, 0, 1, 0};

    //接受门开了的广播
    private BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BleConstant.UNLOCK)){
                icon.setEnabled(true);
                try{
                    closeProgressDialog();
                }catch (Exception e){

                }

                Glide.with(ActivityGuanLiKey.this).load(R.drawable.kaisuo)
//                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .into(icon);
                Intent intent1 = new Intent(KeyGuanLiActivity.KAIMEN);
                sendBroadcast(intent1);
                closeProgressDialog();

                //默认几秒后会自动关锁 大概5秒
                timer= new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        sendBroadcast(new Intent(BleConstant.LOCK));
                        timer.cancel();
                        timer=null;
                    }
                },7000);
            }else if (intent.getAction().equals(BleConstant.LOCK)){
                clear();
                Glide.with(ActivityGuanLiKey.this).load(R.drawable.guansuo)
//                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .into(icon);
            }

        }
    };


    //广播的intent
    private IntentFilter getIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleConstant.UNLOCK);
        intentFilter.addAction(BleConstant.LOCK);
        return intentFilter;
    }
    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_guanli_key;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);

        isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);
        sid=SPUtils.get(this,null,SPContants.LOCK_SESSION,"")+"";

        userPresenter=new UserPresenter(this);
        mContext=ActivityGuanLiKey.this;

        activity = getIntent().getStringExtra("activity");
        leixing = getIntent().getStringExtra("leixing");
        mHousePresenter=new HousePresenter(this);
        keyPresenter=new KeyPresenter(this);
        uid=SPUtils.get(this,null,SPContants.USER_ID,"")+"";
//        SPUtils.put(this,null,SPContants.BATTERY,localKey.getBattery());

        activityType=getIntent().getIntExtra("Tankuang",0);
        //是否弹出弹框 (首次启动的界面)
        if (activityType==2){
            activityType=0;
            if (!"".equals(SPUtils.get(MyApplcation.ctx,null,SPContants.USER_ID,"386")+"")){
                mHousePresenter.queryRedDot(SPUtils.get(MyApplcation.ctx,null,SPContants.USER_ID,"386")+"",MyApplcation.device_token);
            }
        }else {
            //红点显示
            //消息
            updateRedDot(key_img_mess, (Integer) SPUtils.get(getApplication(),null,SPContants.TOTAL_MESSAGE,0));
            //交租
            updateRedDot(key_img_jiaozu,(Integer) SPUtils.get(getApplication(),null,SPContants.YUQI_COUNT,0));
            //维修
            updateRedDot(key_img_weixiu,(Integer) SPUtils.get(getApplication(),null,SPContants.REPAIR_COUNT,0));
            //账单
            updateRedDot(key_img_zhangdan,(Integer) SPUtils.get(getApplication(),null,SPContants.BILL_COUNT,0));
        }

        //判断是否支持ic卡
//        boolean supportIC = DigitUtil.isSupportIC(localKey.getSpecialValue());

//         Log.d("===iccard=",supportIC+"");
        if (leixing.equals("0")) {//管理员
            bottom.setVisibility(View.VISIBLE);
            bottom3.setVisibility(View.GONE);
            icRl.setVisibility(View.VISIBLE);
            key_send.setText("发送密码");
//            if (supportIC){ //支持
//                icRl.setVisibility(View.VISIBLE);
//            }else { //不支持
//                icRl.setVisibility(View.GONE);
//            }
        } else if (leixing.equals("2")) {//租户
            bottom.setVisibility(View.VISIBLE);
            bottom3.setVisibility(View.VISIBLE);
            icRl.setVisibility(View.GONE);
            key_send.setText("发送密码");

        } else {//普通用户
            icRl.setVisibility(View.GONE);
            bottom.setVisibility(View.INVISIBLE);
            bottom3.setVisibility(View.VISIBLE);
        }


//        DigitUtil.isSupportIC()
        clear();
        Glide.with(ActivityGuanLiKey.this).load(R.drawable.guansuo)
//                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(icon);
        cy_mac = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.CHANGYONG_MAC, "");
        key_play = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.KEY_PLAY, "");
        if (key_play.equals("1")) {
            key_tb.setChecked(false);
        } else {
            key_tb.setChecked(true);
        }

        registerReceiver(mReceiver, getIntentFilter());

        //
        if (activity.equals("one")) {
            //请求打开蓝牙
            KeyFragment.mTTLockAPI.requestBleEnable(this);
            localKey = curKeys;
            if (localKey!=null){
                key_title.setText(localKey.getLockAlias());
            }
            String start = String.valueOf(localKey.getStartDate());
            String end = String.valueOf(localKey.getEndDate());
            if (start != null && end != null) {
                if (localKey.getEndDate()>0) {
                    bottom3.setVisibility(View.VISIBLE);
                    shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                    shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                } else {
                    bottom3.setVisibility(View.INVISIBLE);
                }
            }

//            key_title.setText(localKey.getLockAlias());
//            if (leixing.equals("1") || leixing.equals("2")) {//当该钥匙位用户或者租户用户的话，才显示有效期
//
//            }
//            if (leixing.equals("3")){
//                if (localKey.getReset_rent_pass().equals("1")){
//                    try {
//                        showTransactionPassword();
//                    }catch (Exception e){
//
//                    }
//
//                }
//            }

        } else {
            initGreenDao();
            mTTLockAPI=new TTLockAPI(this,mTTLockCallback);
            //请求打开蓝牙
            mTTLockAPI.requestBleEnable(this);
            mTTLockAPI.startBleService(this);

            kensBean = new ArrayList<>();
            keys = new ArrayList<>();
            showProgressDialog("正在获取钥匙......", false);
            if ("".equals(sid)){
                keyPresenter.myKey(uid, "",isLock);
            }else {
                keyPresenter.myKey(sid, "",isLock);
            }

        }




//        setButtonFocusChanged(icon);
    }
    private static final int REQUEST_PERMISSION_REQ_CODE = 1;

    /**
     * 权限请求
     */
    @TargetApi(Build.VERSION_CODES.M)
    public boolean requestPermission(String permission) {
        LogUtil.d("permission:" + permission, true);
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                LogUtil.w("not grant", true);
                return false;
            }
            //请求权限
            LogUtil.d("请求权限", true);
            requestPermissions(new String[]{permission}, REQUEST_PERMISSION_REQ_CODE);
            return false;
        }
        return true;
    }
    /**
     * 数据库初始化
     */
    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "zhujias.db", null);
        Database db = helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
        keyDao = daoSession.getKeyDao();
    }



    //重置密码的pop
    PopupWindow passwordPop=null;

    //重置密码的pop
    public void showTransactionPassword() {
        final View contentView = LayoutInflater.from(this)
                .inflate(R.layout.popwindow_transformation_sure, null);
        passwordPop = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        TextView pop_ok = (TextView) contentView.findViewById(R.id.pop_ok);
        pop_ok.setOnClickListener(this);
        // passwordPop.setAnimationStyle(R.style.popupwindow_anim_style);
        //passwordpop 可点击
        passwordPop.setFocusable(true);

        contentView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        contentView.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
        //点击手机返回键pop关闭
        contentView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (passwordPop != null) {
                        passwordPop.dismiss();
                        ActivityGuanLiKey.this.finish();
                    }
                }
                return false;
            }
        });
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                passwordPop.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {

            case R.id.key_tb:
                if (key_tb.isChecked()) {
                    ByAlert.alert("开门音开启");
                    SPUtils.put(this, null, SPContants.KEY_PLAY, "");//是否播放开锁提示音
                } else {
                    ByAlert.alert("开门音关闭");
                    SPUtils.put(this, null, SPContants.KEY_PLAY, "1");
                }
                break;
            case R.id.key_finish:
                finish();
                break;
            case R.id.key_shezhi:// 设置
                PuPoWindow(v);

                break;

            //设置 pop的item点击

            case R.id.set_shezhi://设置
                popupWindow.dismiss();
                intent = new Intent(this, ActivityKeySheZhiTwo.class);
                intent.putExtra("lockid", localKey.getLockId());
                intent.putExtra("keyid", localKey.getKeyId());
                intent.putExtra("lockAlias", localKey.getLockAlias());
                startActivity(intent);
                break;
            case R.id.set_putong://普通模式
                popupWindow.dismiss();
                ByAlert.alert("设置成功");
                SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
//                SPUtils.put(this,null,SPContants.);
                break;
            case R.id.set_mensuo://门锁模式
                popupWindow.dismiss();
                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                intent = new Intent(this, ActivityKeyXuanZe.class);
                startActivityForResult(intent, 101);
                break;
            case R.id.key_send_yaoshi:// 发送钥匙

                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                if (localKey.getHas_valid_rent().equals("0")) {
                    intent = new Intent(this, ActivitySendKey.class);
                    intent.putExtra("lockid", localKey.getLockId());
                    intent.putExtra("type", leixing);
                    intent.putExtra("start", localKey.getStartDate());
                    intent.putExtra("end", localKey.getEndDate());
                    startActivity(intent);
                } else {
                    ByAlert.alert("该锁已有合法租户，管理员不能发送钥匙");
                }

                break;
            case R.id.key_send_pass:// 发送密码

                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                if (localKey.getHas_valid_rent().equals("0")) {

                    intent = new Intent(this, ActivityFaSongPass.class);
                    intent.putExtra("lockid", localKey.getLockId());
                    intent.putExtra("lockName",localKey.getLockAlias());
                    startActivity(intent);
//                    if (localKey.getTypes().equals("0")) {//管理员--跳转到发送密码
//                        intent = new Intent(this, SendPassActivity.class);
//                        intent.putExtra("lockid", localKey.getLockId());
//                        intent.putExtra("mac", localKey.getLockMac());
//                        startActivity(intent);
//                    } else {//租户--跳转到设置密码
//                        intent = new Intent(this, SetPassActivity.class);
//                        intent.putExtra("lockid", localKey.getLockId());
//                        intent.putExtra("lockMac", localKey.getLockMac());
//                        intent.putExtra("end", localKey.getEndDate());
//                        startActivity(intent);
//                    }
                } else {
                    ByAlert.alert("该锁已有合法租户，管理员不能发送密码");
                }
                break;
            case R.id.key_guanli:// 用户管理

                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                intent = new Intent(this, ActivityYongHu.class);
                intent.putExtra("lockid", localKey.getLockId());
                intent.putExtra("lockMac", localKey.getLockMac());
                intent.putExtra("type", leixing);
                startActivity(intent);

//                intent = new Intent(this, YongHuAdminActivity.class);
//                intent.putExtra("lockid", localKey.getLockId());
//                intent.putExtra("lockMac", localKey.getLockMac());
//
//                startActivity(intent);
                break;
            case R.id.key_jilu:// 开锁记录
                intent = new Intent(this, ActivityKaiSuoJiLuOne.class);
                intent.putExtra("keyid", localKey.getKeyId());
                intent.putExtra("lockid", localKey.getLockId());
                startActivity(intent);
                break;

            case R.id.key_tv_mess://消息
//                if (activity.equals("one")) {//从锁界面跳转过来，直接返回，跳转到消息界面
//                    intent = new Intent();
//                    setResult(110, intent);
//                    finish();
//                } else {//处于锁模式，直接跳转到主界面
                    intent = new Intent(this, MainActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
//                }
                break;
            case R.id.key_tv_jiaozu://交租
                intent = new Intent(this, ActivityMySign.class);
                startActivity(intent);
                break;
            case R.id.key_tv_weixiu://维修
                intent = new Intent(this, ActivityGuanJia.class);
                startActivity(intent);
                break;
            case R.id.key_tv_zhangdan://账单
//                intent = new Intent(this, WebActivity.class);
                intent = new Intent(this,RentingOrderListActivity.class);
                intent.putExtra(
                        "url", NetPublicConstant.WEB_URL02
                                + "/wallet/index?uid="
                                + uid + "&psw=" + (SPUtils.get(this, null, SPContants.PASSWORD, "") + ""));
                intent.putExtra("title", "资金交易明细");
                startActivity(intent);
                break;

            case R.id.icon://开锁
            icon.setEnabled(false);
            if (localKey.getHas_valid_rent().equals("0")) {
                if (activity.equals("one")) { //非纯门锁
                    KeyFragment.bleSession.setOperation(Operation.DOUNLOCK);
                    KeyFragment.mTTLockAPI.connect(localKey.getLockMac());
                    showProgressDialog("正在开锁...", true);
                    clear();
                    Glide.with(ActivityGuanLiKey.this).load(R.drawable.keyfiff)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(icon);
                }else { //纯门锁
//                    bleSession.setOperation(Operation.DOUNLOCK);
//                    mTTLockAPI.connect(localKey.getLockMac());
                    mTTLockAPI.connect(localKey.getLockMac());
                    bleSession.setOperation(Operation.DOUNLOCK);
                    bleSession.setLockmac(localKey.getLockMac());
                    showProgressDialog("正在开锁...", true);
                    clear();
                    Glide.with(ActivityGuanLiKey.this).load(R.drawable.keyfiff)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(icon);
                }
            } else {
                    ByAlert.alert("该锁已有合法租户，管理员不能发送钥匙");
                }
                break;

            case R.id.icRl://ic卡
                Intent intent1 = new Intent(this, ActivityICCardList.class);
                startActivity(intent1);
                break;

            default:
                break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 101 && resultCode == 105) {
            Bundle bundle = data.getExtras();
            String macs = bundle.getString("mac");
            String types = bundle.getString("type");
            leixing = types;
            localKey = (Key) bundle.getSerializable("key");

            key_title.setText(localKey.getLockAlias());

            SPUtils.put(MyApplcation.ctx, null, SPContants.CHANGYONG_MAC, macs);//锁名称
            SPUtils.put(MyApplcation.ctx, null, SPContants.CHANGYONG_TYPE, types);//锁类型
            SPUtils.put(MyApplcation.ctx,null,SPContants.LOCK_TYPE,1);

            ByAlert.alert("设置成功");

            String start = String.valueOf(localKey.getStartDate());
            String end = String.valueOf(localKey.getEndDate());
            if (types.equals("0")) {//管理员
                bottom.setVisibility(View.VISIBLE);
                bottom3.setVisibility(View.GONE);
                key_send.setText("发送密码");
            } else if (types.equals("2")) {//租户
                bottom.setVisibility(View.VISIBLE);
                bottom3.setVisibility(View.VISIBLE);
                shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                key_send.setText("发送密码");
            } else {//普通用户
                bottom.setVisibility(View.INVISIBLE);

                if (localKey.getEndDate()>0){ //有时间限制
                    bottom3.setVisibility(View.VISIBLE);
                    shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                    shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                }else {//没有时间限制
                    bottom3.setVisibility(View.GONE);
                }
            }


//            if (types.equals("1") || types.equals("3")) {//当该钥匙位用户或者租户用户的话，才显示有效期
//
//                if (start != null && end != null) {
//                    if (start.equals("0")) {
//                        bottom3.setVisibility(View.INVISIBLE);
//                    } else {
//                        bottom3.setVisibility(View.VISIBLE);
//
//                    }
//                }
//            }

        }
    }

    /**
     * 钥匙搜索切换框
     */
    private void PuPoWindow(View v) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.item_shezhi, null);
        TextView set_shezhi = (TextView) view
                .findViewById(R.id.set_shezhi);
        TextView set_putong = (TextView) view
                .findViewById(R.id.set_putong);
        TextView set_mensuo = (TextView) view
                .findViewById(R.id.set_mensuo);

        set_shezhi.setOnClickListener(this);
        set_putong.setOnClickListener(this);
        set_mensuo.setOnClickListener(this);
        popupWindow = new PopupWindow(view, FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(v);
    }


    private void clear(){
        icon.setBackgroundResource(0);
    }
    /**
     * 按钮焦点改变
     */
    public final static View.OnFocusChangeListener buttonOnFocusChangeListener = new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));
                v.setBackgroundDrawable(v.getBackground());
            } else {
                v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
                v.setBackgroundDrawable(v.getBackground());
            }
        }
    };


    /**
     * 按钮触碰按下效果
     */
    public final static View.OnTouchListener buttonOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));
                v.setBackgroundDrawable(v.getBackground());
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
                v.setBackgroundDrawable(v.getBackground());
            }
            return false;
        }
    };


    @Override
    public void finish() {
        super.finish();
        try {
            unregisterReceiver(mReceiver);
        }catch (Exception e){
            Log.d(getLocalClassName(),e.toString());
        }
    }

    /**
     * 设置图片按钮获取焦点改变状态
     */
    public final static void setButtonFocusChanged(View inView) {
        inView.setOnTouchListener(buttonOnTouchListener);
        inView.setOnFocusChangeListener(buttonOnFocusChangeListener);
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }


    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity!=null){
            if (entity.getEventType() == HousePresenter.queryRedDot_success){
                Log.d("hongdian=","true");
                RedDotBean mRedDotBean= (RedDotBean) entity.getData();
                showDialog(mRedDotBean);//展示所有弹框
                saveRedDotData(mRedDotBean);//保存红点数据

            }else if (entity.getEventType() == HousePresenter.queryRedDot_fail){
                if (entity.getCode().equals("-2")||entity.getMsg().equals("登录已失效，请重新登录")){
                    ByAlert.alert("登录已失效，请重新登录");
                    exit();
                    startActivity(new Intent(this,LoginActivity.class));
                }
//                Log.d("hongdian=","false");
//                ByAlert.alert("红点数据请求失败");
            } else if (entity.getEventType() == KeyPresenter.mykeys_success) {//我的钥匙列表
                try{
                    closeProgressDialog();
                }catch (Exception e){

                }
                kensBean = (List<KeysBean>) entity.getData();
                Log.d("=====keji==",kensBean.toString());
                if (kensBean != null) {
                    if (kensBean.size() > 0) {
                        if (keys==null){
                            keys=new ArrayList<>();
                        }else {
                            if (keys.size()>0){
                                keys.clear();
                            }
                        }
                        //清空本地并重新保存数据
                        DbService.deleteAllKey();
                        for (int i = 0; i < kensBean.size(); i++) {
                            Key key = new Key();
                            key.setAccessToken(MyPreference.getStr(mContext,
                                    MyPreference.ACCESS_TOKEN));
                            if (kensBean.get(i).getType().equals("0")) {
                                key.setAdmin(true);
                            } else {
                                key.setAdmin(false);
                            }
                            key.setLockVersion(gson.toJson(kensBean.get(i).getLock_version()));
                            key.setLockName(kensBean.get(i).getLock_name());
                            key.setLockMac(kensBean.get(i).getLock_mac());
                            key.setAdminPs(kensBean.get(i).getAdminPwd());
                            key.setUnlockKey(kensBean.get(i).getLock_key());
                            key.setAdminKeyboardPwd(kensBean.get(i).getNoKeyPwd());
                            key.setDeletePwd(kensBean.get(i).getDeletePwd());
                            key.setPwdInfo("");
                            key.setTimestamp(0);
                            key.setAesKeystr(kensBean.get(i).getAesKeyStr());
                            // key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(currentTimeMillis()));
                            key.setTimezoneRawOffset(Integer.parseInt(get(this, null, SPContants.SHIQU, "") + ""));

                            //上面是开锁用到的必要数据，下面这些是一些操作数据
                            key.setLockId(kensBean.get(i).getLock_id());
                            key.setKeyId(kensBean.get(i).getKey_id());
                            key.setLockAlias(kensBean.get(i).getLock_alias());
                            key.setStartDate(parseLong(kensBean.get(i).getStart()));
                            key.setEndDate(parseLong(kensBean.get(i).getEnd()));
                            key.setUser_type(kensBean.get(i).getUser_type());
                            key.setStatus(kensBean.get(i).getStatus());
                            key.setPush(kensBean.get(i).getPush());
                            key.setHouse_no(kensBean.get(i).getHouse_no());
                            key.setTypes(kensBean.get(i).getType());
                            key.setKeyStatus(kensBean.get(i).getKeyStatus());
                            key.setBattery(kensBean.get(i).getPower());
                            key.setLock_type(kensBean.get(i).getLock_type());
                            key.setLockFlagPos(Integer.parseInt(kensBean.get(i).getLockFlagPos()));
                            key.setHas_valid_rent(kensBean.get(i).getHas_valid_rent());
                            key.setReset_rent_pass(kensBean.get(i).getReset_rent_pass());
                            key.setId(keyDao.insert(key));
                            keys.add(key);

                        }
                        //清空本地并重新保存数据
                        DbService.saveKeyList(keys);

                        for (int i = 0; i < keys.size(); i++) {
                            if (keys.get(i).getLockMac().equals(cy_mac)) {
                                localKey = keys.get(i);
                                Log.d("=====tt",localKey.toString());
                                lockid=localKey.getLockId();
                                key_title.setText(localKey.getLockAlias());
                                if (localKey.getTypes().equals("2")){
                                    if (localKey.getReset_rent_pass().equals("1")){
                                        showTransactionPassword();
                                    }
                                }
                                String start = String.valueOf(localKey.getStartDate());
                                String end = String.valueOf(localKey.getEndDate());
                                if (start != null && end != null) {
                                    if (start.equals("0")) {
                                        bottom3.setVisibility(View.INVISIBLE);
                                    } else {
                                        bottom3.setVisibility(View.VISIBLE);
                                        shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                                        shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                                    }
                                }
//                                if (leixing.equals("1") || leixing.equals("2")) {//当该钥匙位用户或者租户用户的话，才显示有效期
//
//                                }
                            }
                        }

//                        //刷新当前的key
//                        if (position!=-1){
//                            localKey = keys.get(position);
//                        }

                        if (localKey == null) {
                            ByAlert.alert("保存的锁不存在了");
                            SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                            SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                            Intent intent = new Intent(ActivityGuanLiKey.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        } else {//锁存在的时候   判断异常吗，然后直接跳转到主界面吧
                            String type = localKey.getStatus();
                            if (type.equals("110402") || type.equals("110405") || type.equals("110408") || type.equals("110410")) {
                                ByAlert.alert("该钥匙处于异常状态");
//                                SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
//                                SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                                Intent intent = new Intent(ActivityGuanLiKey.this, MainActivity.class);
                                intent.putExtra("unlock",type);
                                startActivity(intent);
                                finish();
                            }
                            if (localKey.getEndDate() != 0) {
                                Long dq_time = System.currentTimeMillis() / 1000;//当前时间
                                Long sx_time = localKey.getEndDate();//锁的实效时间
                                if (dq_time >= sx_time) {
                                    ByAlert.alert("该钥匙已失效");
                                    SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                                    SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                                    Intent intent = new Intent(ActivityGuanLiKey.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        }
                    } else {
                        ByAlert.alert("保存的锁不存在了");
                        SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                        SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                        Intent intent = new Intent(ActivityGuanLiKey.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            } else if (entity.getEventType() == KeyPresenter.mykeys_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }
            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_addIcCard_success){//添加ic卡
                ByAlert.alert("ic卡添加成功");
            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_addIcCard_fail){


            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_delIcCard_success){
                //发送删除ic卡成功的广播
               sendBroadcast(new Intent(BleConstant.DELETE_ICCARD));

            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_delIcCard_fail){
                ByAlert.alert(entity.getMsg());

            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_clearIcCard_success){
                //发送删除ic卡列表的广播
                sendBroadcast(new Intent(BleConstant.CLEAR_ICCARD));

            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_clearIcCard_fail){
                ByAlert.alert(entity.getMsg());
            } else if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData();
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }else if (entity.getEventType() == UserPresenter.uploadjilu_success) {//上传记录的地方，在开锁后上传开锁记录
                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS, "");//上传成功之后清空掉操作日志
                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS_LOCKID, "");
            } else if (entity.getEventType() == UserPresenter.uploadjilu_fail) {
                if (entity.getData() instanceof ServerError||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }

            }

        }

    }

    //显示dialog
    public  void showDialog(RedDotBean mRedDotBean){
        //dialog type  1  尚有租金逾期未交  2 尚有附件清单未确认 3 尚有未完成的签约 4 尚有申请签约的房源

        if (MyApplcation.mShenQin==null){
            //经纪人去选租客
            if (mRedDotBean.getApply_list().size()>0){
                MyApplcation.mShenQin= new ListDialog(
                        ActivityGuanLiKey.this,
                        "尚有申请签约的房源",
                        mRedDotBean.getApply_list(),
                        4);
                MyApplcation.mShenQin.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mShenQin.cancel();
                        MyApplcation.mShenQin=null;
                    }
                });
                if (mRedDotBean.getApply_list().size()>12){
                    MyApplcation.mShenQin.setListDialogHeigh();
                }
                MyApplcation.mShenQin.show();
            }
        }

        if (MyApplcation.mQianDing==null){
            //租客签订合同
            if (mRedDotBean.getNeed_sign_contract_list().size()>0){
                MyApplcation.mQianDing= new ListDialog(
                        ActivityGuanLiKey.this,
                        "尚有未完成的签约",
                        mRedDotBean.getNeed_sign_contract_list(),
                        3);

                MyApplcation.mQianDing.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mQianDing.cancel();
                        MyApplcation.mQianDing=null;
                    }
                });
                if (mRedDotBean.getNeed_sign_contract_list().size()>12){
                    MyApplcation.mQianDing.setListDialogHeigh();
                }
                MyApplcation.mQianDing.show();
            }
        }

        if (MyApplcation.mFujian==null){
            //租客确定附件单
            if (mRedDotBean.getNeed_confirm_facility_list().size()>0){
                List<String> confirm = new ArrayList<>();
                List<String> contract_no = new ArrayList<>();
                for (int i=0;i< mRedDotBean.getNeed_confirm_facility_list().size();i++){
                    contract_no.add(mRedDotBean.getNeed_confirm_facility_list().get(i).getContract_no());
                    confirm.add(getStringContent(mRedDotBean.getNeed_confirm_facility_list().get(i)));
                }

                MyApplcation.mFujian= new ListDialog(
                        ActivityGuanLiKey.this,
                        "尚有附件清单未确认",
                        confirm,
                        2,contract_no);
                MyApplcation.mFujian.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mFujian.cancel();
                        MyApplcation.mFujian=null;
                    }
                });
                if (mRedDotBean.getNeed_confirm_facility_list().size()>2){
                    MyApplcation.mFujian.setListDialogHeigh();
                }
                MyApplcation.mFujian.show();
            }
        }
        if (MyApplcation.mYuQi==null){

            //租客逾期支付
            if (mRedDotBean.getOverdue_list().size()>0){
                MyApplcation.mYuQi= new ListDialog(
                        ActivityGuanLiKey.this,
                        "尚有租金逾期未交",
                        mRedDotBean.getOverdue_list(),
                        1);
                MyApplcation.mYuQi.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mYuQi.cancel();
                        MyApplcation.mYuQi=null;
                    }
                });
                if (mRedDotBean.getOverdue_list().size()>12){
                    MyApplcation.mYuQi.setListDialogHeigh();
                }
                MyApplcation.mYuQi.show();
            }
        }
    }

    //是否显示红点
    public void updateRedDot(ImageView imageView,int count){

        if (count>0){
            imageView.setVisibility(View.VISIBLE);
        }else {
            imageView.setVisibility(View.GONE);
        }
    }

    //存储红点
    public  void saveRedDotData(RedDotBean mRedDotBean) {
        // ImageView key_img_mess, key_img_jiaozu, key_img_weixiu, key_img_zhangdan;//消息，交租，维修，账单消息 红点显示
        if (mRedDotBean.getNeed_write_facility_count()>0){ //需要填写附件单的合同数
            SPUtils.put(ActivityGuanLiKey.this,null,SPContants.FUJIAN_ORDER,true);
        }
        //消息
        updateRedDot(key_img_mess,mRedDotBean.getUnread_count().getTotal());
        //交租
        updateRedDot(key_img_jiaozu,mRedDotBean.getOverdue_count());
        //维修
        updateRedDot(key_img_weixiu,mRedDotBean.getRepair_count());
        //账单
        updateRedDot(key_img_zhangdan,mRedDotBean.getBill_count());


        SPUtils.put(ActivityGuanLiKey.this,null,SPContants.TOTAL_MESSAGE,mRedDotBean.getUnread_count().getTotal());//消息总数
        SPUtils.put(ActivityGuanLiKey.this,null,SPContants.SYSTEM_MESSAGE,mRedDotBean.getUnread_count().getSystem());//系统消息
        SPUtils.put(ActivityGuanLiKey.this,null,SPContants.CONTRANCT_MESSAGE,mRedDotBean.getUnread_count().getContract());//签约消息
        SPUtils.put(ActivityGuanLiKey.this,null,SPContants.LOCK_MESSAGE,mRedDotBean.getUnread_count().getLock());//锁消息
        SPUtils.put(ActivityGuanLiKey.this,null,SPContants.REPAIR_COUNT,mRedDotBean.getRepair_count());//未维修数
        SPUtils.put(ActivityGuanLiKey.this,null,SPContants.BILL_COUNT,mRedDotBean.getBill_count());//账单数
    }

    //TODO:
    private <K, V extends Parcelable> void broadcastUpdate(String action, K key, V value) {
        final Intent intent = new Intent(action);
        if (key != null) {
            Bundle bundle = new Bundle();
            bundle.putParcelable((String) key, value);
            intent.putExtras(bundle);

        }
        MyApplcation.ctx.sendBroadcast(intent);
    }

    private Handler handler = new Handler();
    private void toast(final String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 通通锁回调
     */
    public TTLockCallback mTTLockCallback = new TTLockCallback() {
        long cardno;
        @Override
        public void onFoundDevice(ExtendedBluetoothDevice extendedBluetoothDevice) {
            Log.d("=====tt","onFoundDevice()");
            //发现设备并广播
            broadcastUpdate(BleConstant.ACTION_BLE_DEVICE, BleConstant.DEVICE, extendedBluetoothDevice);
            String accessToken = MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN);
            Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, extendedBluetoothDevice.getAddress());
            if (localKey != null) {
                switch (bleSession.getOperation()) {
                    case UNLOCK:


//                        if(extendedBluetoothDevice.isTouch()){}
//                            mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                    case SET_ADMIN_KEYBOARD_PASSWORD:
                        break;
                    case SET_DELETE_PASSWORD:
                        break;
                    case SET_LOCK_TIME:
                        if (extendedBluetoothDevice.getAddress().equals(bleSession.getLockmac()))
                            mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                    case RESET_KEYBOARD_PASSWORD:
                        if (ActivityYongHu.addLock) {
                            ActivityYongHu.addLock = false;
                            mTTLockAPI.connect(extendedBluetoothDevice);
                        }
                        break;
                    case RESET_EKEY:
                    case RESET_LOCK:

                        mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                    case GET_LOCK_TIME:
                    case GET_OPERATE_LOG:
                        if (extendedBluetoothDevice.getAddress().equals(bleSession.getLockmac()))
                            mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                }
            }
        }

        @Override
        public void onDeviceConnected(ExtendedBluetoothDevice extendedBluetoothDevice) {
            Log.d("=====tt","onDeviceConnected()");
//            String accessToken = MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN);
//            //TODO:
//            localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, extendedBluetoothDevice.getAddress());
            String openid = String.valueOf(SPUtils.get(ActivityGuanLiKey.this, null, SPContants.OPENID, ""));
            int id = openid == null || openid.equals("") ? Integer.parseInt(SPUtils.get(ActivityGuanLiKey.this, null, SPContants.USER_ID, "") + "") : Integer.parseInt(SPUtils.get(ActivityGuanLiKey.this, null, SPContants.OPENID, "") + "");
            Log.d("=====tt","id=="+id);
            operateSuccess = false;
            switch (bleSession.getOperation()) {
                case ADD_ADMIN:
                    //TODO:判断本地是否存在
                    mTTLockAPI.addAdministrator(extendedBluetoothDevice);
                    break;
                case UNLOCK:
                case CLICK_UNLOCK:
                    if (localKey != null) {//本地存在锁
                        if (localKey.isAdmin())
                            mTTLockAPI.unlockByAdministrator(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), currentTimeMillis(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                        else
                            mTTLockAPI.unlockByUser(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getStartDate() * 1000, localKey.getEndDate() * 1000, localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    }
                    break;
                case SET_ADMIN_KEYBOARD_PASSWORD://管理码
                    mTTLockAPI.setAdminKeyboardPassword(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), bleSession.getPassword());
                    break;
                case SET_DELETE_PASSWORD://删除码
                    mTTLockAPI.setDeletePassword(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), bleSession.getPassword());
                    break;
                case SET_LOCK_TIME://设置锁时间
                    mTTLockAPI.setLockTime(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getUnlockKey(), currentTimeMillis(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case RESET_KEYBOARD_PASSWORD://重置键盘密码
                    mTTLockAPI.resetKeyboardPassword(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr());
                    break;
                case RESET_EKEY://重置电子钥匙 锁标志位+1
                    mTTLockAPI.resetEKey(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getLockFlagPos() + 1, localKey.getAesKeystr());
                    break;
                case RESET_LOCK://重置锁

                    break;
                case GET_OPERATE_LOG://获取操作日志
                    mTTLockAPI.getOperateLog(extendedBluetoothDevice, localKey.getLockVersion(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case GET_LOCK_TIME://获取锁时间
                    mTTLockAPI.getLockTime(extendedBluetoothDevice, localKey.getLockVersion(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case LOCKCAR_UP://车位锁升
                    if (localKey.isAdmin())
                        mTTLockAPI.lockByAdministrator(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr());
                    else
                        mTTLockAPI.lockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getStartDate(), localKey.getEndDate(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
//                    mTTLockAPI.lockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), 1489990922165l, 1490077322165l, localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case LOCKCAR_DOWN://车位锁降
                    if (localKey.isAdmin())
                        mTTLockAPI.unlockByAdministrator(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), currentTimeMillis(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    else
                        mTTLockAPI.unlockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getStartDate(), localKey.getEndDate(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
//                    mTTLockAPI.unlockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), 1489990922165l, 1490077322165l, localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case DELETE_ONE_KEYBOARDPASSWORD://这里的密码类型传0
                    mTTLockAPI.deleteOneKeyboardPassword(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), 0, bleSession.getPassword(), localKey.getAesKeystr());
                    break;
                case ADDICCARD://添加ic卡

                    mTTLockAPI.addICCard(extendedBluetoothDevice,
                            0,
                            ActivityAddICCard.localKey.getLockVersion(),
                            ActivityAddICCard.localKey.getAdminPs(),
                            ActivityAddICCard.localKey.getUnlockKey(),
                            ActivityAddICCard.localKey.getLockFlagPos(),
                            ActivityAddICCard.localKey.getAesKeystr());
                    break;

                case DELETEICCARD:
                    mTTLockAPI.deleteICCard(extendedBluetoothDevice,
                            0,
                            ActivityICCardList.localKey.getLockVersion(),
                            ActivityICCardList.localKey.getAdminPs(),
                            ActivityICCardList.localKey.getUnlockKey(),
                            ActivityICCardList.localKey.getLockFlagPos(),
                            Long.parseLong(ActivityICCardList.cardNo),
                            ActivityICCardList.localKey.getAesKeystr());
                    break;

                case CLEARICCARD:
                    mTTLockAPI.clearICCard(extendedBluetoothDevice,
                            0,
                            ActivityICCardList.localKey.getLockVersion(),
                            ActivityICCardList.localKey.getAdminPs(),
                            ActivityICCardList.localKey.getUnlockKey(),
                            ActivityICCardList.localKey.getLockFlagPos(),
                            ActivityICCardList.localKey.getAesKeystr());
                    break;

                case DOUNLOCK:
                    Log.d("=====tt","localKey=="+localKey.toString());
                    if (ActivityGuanLiKey.localKey.getUser_type().equals("0")){//管理员开锁
                        mTTLockAPI.unlockByAdministrator(extendedBluetoothDevice,
                                id,
                                ActivityGuanLiKey.localKey.getLockVersion()==null?"":ActivityGuanLiKey.localKey.getLockVersion(),
                                ActivityGuanLiKey.localKey.getAdminPs(),
                                ActivityGuanLiKey.localKey.getUnlockKey(),
                                ActivityGuanLiKey.localKey.getLockFlagPos(),
                                System.currentTimeMillis(),
                                ActivityGuanLiKey.localKey.getAesKeystr(),
                                ActivityGuanLiKey.localKey.getTimezoneRawOffset());
                    }else {//租客开锁
                        mTTLockAPI.unlockByUser(extendedBluetoothDevice,
                                openid == null || openid.equals("") ? Integer.parseInt(SPUtils.get(ActivityGuanLiKey.this, null, SPContants.USER_ID, "") + "") : Integer.parseInt(SPUtils.get(ActivityGuanLiKey.this, null, SPContants.OPENID, "") + ""),
                                ActivityGuanLiKey.localKey.getLockVersion()==null?"":ActivityGuanLiKey.localKey.getLockVersion(),
                                ActivityGuanLiKey.localKey.getStartDate()*1000,
                                ActivityGuanLiKey.localKey.getEndDate()*1000,
                                ActivityGuanLiKey.localKey.getUnlockKey(),
                                ActivityGuanLiKey.localKey.getLockFlagPos(),
                                ActivityGuanLiKey.localKey.getAesKeystr(),
                                ActivityGuanLiKey.localKey.getTimezoneRawOffset());
                    }

                    break;
//                case SEARCHICCARD://查询ic卡
//                    mTTLockAPI.searchDeviceFeature(extendedBluetoothDevice,0, ActivityICCardList.localKey.getLockVersion(),
//                            ActivityICCardList.localKey.getAdminPs(),ActivityICCardList.localKey.getUnlockKey(),
//                            ActivityICCardList.localKey.getLockFlagPos(),ActivityICCardList.localKey.getAesKeystr());
//                    break;

            }
        }

        @Override
        public void onDeviceDisconnected(ExtendedBluetoothDevice extendedBluetoothDevice) {
            //默认是开门标志
            Log.d("=====tt","onDeviceDisconnected()");
            diconectNum++;
            if(!operateSuccess){ //设备未连接
                if (diconectNum<2) {
                    //重连一次
                    mTTLockAPI.connect(extendedBluetoothDevice);
                } else {
                    //断开连接
                    broadcastUpdate(BleConstant.ACTION_BLE_DISCONNECTED, BleConstant.DEVICE, extendedBluetoothDevice);
                    diconectNum=0;
                }
            }else {
                //断开连接
                broadcastUpdate(BleConstant.ACTION_BLE_DISCONNECTED, BleConstant.DEVICE, extendedBluetoothDevice);
            }
            try {
                ((BaseOtherActivity) curActivity).closeProgressDialog();
            } catch (Exception e) {

            }
        }

        @Override
        public void onGetLockVersion(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, int i2, int i3, int i4, Error error) {

        }

        @Override
        public void onAddAdministrator(ExtendedBluetoothDevice extendedBluetoothDevice, String lockVersionString, String adminPs, String unlockKey, String adminKeyboardPwd, String deletePwd, String pwdInfo, long timestamp, String aesKeystr, int feature, String modelNumber, String hardwareRevision, String firmwareRevision, Error error) {
            Log.d("=====tt","onAddAdministrator()");
            Log.d("onAddAdministrator","添加管理员:" + error + "," + "lockVersion--->" + lockVersionString + "电量------>" + extendedBluetoothDevice.getBatteryCapacity());
            operateSuccess = true;
            if (error == Error.SUCCESS) {
//                curActivity.finish();
                //TODO:save数据


                final Key key = new Key();
                key.setAccessToken(MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN));
                key.setAdmin(true);
                key.setLockVersion(lockVersionString);
                key.setLockName(extendedBluetoothDevice.getName());
                key.setLockMac(extendedBluetoothDevice.getAddress());
                key.setAdminPs(adminPs);
                key.setUnlockKey(unlockKey);
                key.setAdminKeyboardPwd(adminKeyboardPwd);
                key.setDeletePwd(deletePwd);
                key.setPwdInfo(pwdInfo);
                key.setTimestamp(timestamp);
                key.setAesKeystr(aesKeystr);
                key.setSpecialValue(feature);
                key.setBattery(extendedBluetoothDevice.getBatteryCapacity());

//                key.setLockAlias(ActivitySheBei.alisa);
                //获取当前时区偏移量 可以传入-1 不考虑时区问题
                key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(System.currentTimeMillis()));
                key.setModelNumber(modelNumber);
                key.setHardwareRevision(hardwareRevision);
                key.setFirmwareRevision(firmwareRevision);
                SaveKeyBean.saveData("1", key);
                toast("锁添加成功，正在上传服务端进行初始化操作");
                Log.d("addd===",extendedBluetoothDevice.getName()+ActivitySheBei.alisa);
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid)){
                    keyPresenter.getAddMain(uid, "6323", extendedBluetoothDevice.getName()+ActivitySheBei.alisa,
                            extendedBluetoothDevice.getName()+ActivitySheBei.alisa, extendedBluetoothDevice.getAddress(), unlockKey, "0",
                            aesKeystr.toString(), lockVersionString.toString(), adminPs, adminKeyboardPwd, deletePwd, pwdInfo, timestamp + "", feature + "",extendedBluetoothDevice.getBatteryCapacity());
                }else {
                    keyPresenter.getAddMain(sid, "6323", extendedBluetoothDevice.getName()+ActivitySheBei.alisa,
                            extendedBluetoothDevice.getName()+ActivitySheBei.alisa, extendedBluetoothDevice.getAddress(), unlockKey, "0",
                            aesKeystr.toString(), lockVersionString.toString(), adminPs, adminKeyboardPwd, deletePwd, pwdInfo, timestamp + "", feature + "",extendedBluetoothDevice.getBatteryCapacity());
                }


            } else {//失败
                toast(error.getErrorMsg());
            }
        }

        @Override
        public void onResetEKey(ExtendedBluetoothDevice extendedBluetoothDevice, final int lockFlagPos, Error error) {
            operateSuccess = true;
            Log.d("=====tt","onResetEKey()");
            if (error == Error.SUCCESS) {

                localKey.setLockFlagPos(lockFlagPos);
                DbService.updateKey(localKey);
                toast("重置电子钥匙成功，锁标志位:" + lockFlagPos);

            } else
                toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetLockName(ExtendedBluetoothDevice extendedBluetoothDevice, String s, Error error) {

        }

        @Override
        public void onSetAdminKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, String adminCode, Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                localKey.setAdminKeyboardPwd(adminCode);
                DbService.updateKey(localKey);
                toast("设置管理码成功:" + adminCode);
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetDeletePassword(ExtendedBluetoothDevice extendedBluetoothDevice, String deleteCode, Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {
                localKey.setDeletePwd(deleteCode);
                DbService.updateKey(localKey);
                toast("设置清空码成功:" + deleteCode);
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onUnlock(ExtendedBluetoothDevice extendedBluetoothDevice, int uid, int uniqueid, long lockTime, Error error) {
            Log.d("=====tt","onUnlock==error"+error);
            operateSuccess = true;
            if (error == Error.SUCCESS) {
                //设置锁时间
                long oldServiceTime = (long) get(ActivityGuanLiKey.this, null, SPContants.oldServiceTime, 0l);
                long oldPhoneTime = (long) get(ActivityGuanLiKey.this, null, SPContants.oldPhoneTime, 0l);
                long times = System.currentTimeMillis()-oldPhoneTime+oldServiceTime;
                Log.d("===settime",times+"");
                mTTLockAPI.setLockTime(extendedBluetoothDevice,
                        0,
                        localKey.getLockVersion(),
                        localKey.getUnlockKey(),
                        times,
                        localKey.getLockFlagPos(),
                        localKey.getAesKeystr(),
                        localKey.getTimezoneRawOffset());

            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
            try {
                closeProgressDialog();
            } catch (Exception e) {
            }
        }

        @Override
        public void onLock(ExtendedBluetoothDevice extendedBluetoothDevice, int uniqueid, Error error) {
            Log.d("====iccard=","onLock==自动关锁error");
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                toast("关锁成功");
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {
                //获取操作日志
                switch (bleSession.getOperation()) {
                    case ADDICCARD: //设置时间 添加iccard
                        userPresenter.addIcCard(uid,ActivityAddICCard.localKey.getLockId(),cardno+"",ActivityAddICCard.icCardName,ActivityAddICCard.startDate,ActivityAddICCard.endDate);
                        ActivityGuanLiKey.this.sendBroadcast(new Intent(BleConstant.ADD_ICCARD));
                        break;
                    case DOUNLOCK: //开锁
                        mTTLockAPI.getOperateLog(extendedBluetoothDevice, localKey.getLockVersion(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                        break;

                    case CHECKDEVICETIME: //校验时间 成功
                        sendBroadcast(new Intent(BleConstant.CHECKLOCKTIME));
                        break;
                }
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onGetLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, long lockTime, Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                Log.d("===onGetLockTime",lockTime+"");
                Intent intent = new Intent(BleConstant.DEVICETIME);
                intent.putExtra("locktime",lockTime);
                sendBroadcast(intent);
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onResetKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, final String pwdInfo, final long timestamp, final Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                toast("重码成功置键盘密");
                localKey.setPwdInfo(pwdInfo);
                localKey.setTimestamp(timestamp);
                DbService.updateKey(localKey);

                // 发送广播通知锁重置键盘密码成功
                Intent intent2 = new Intent("suo_ok");
                ActivityGuanLiKey.this.sendBroadcast(intent2);
            } else {
                toast(error.getErrorMsg());
            }
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetMaxNumberOfKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onResetKeyboardPasswordProgress(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onResetLock(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {

        }

        @Override
        public void onAddKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int i, String s, long l, long l1, Error error) {

        }

        @Override
        public void onModifyKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int i, String s, String s1, Error error) {

        }

        @Override
        public void onDeleteOneKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int keyboardPwdTypei, String deletedPwd, Error error) {
            if (error == Error.SUCCESS) {
                toast("通过蓝牙删除密码成功");
//                if(operateCallback != null)
//                    operateCallback.onSuccess();
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onDeleteAllKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {

        }

        @Override
        public void onGetOperateLog(ExtendedBluetoothDevice extendedBluetoothDevice, String records, Error error) {
            Log.d("====iccard=","onUnlock==error"+error);
            operateSuccess = true;
            toast("门开了");
            //发送门开广播
            ActivityGuanLiKey.this.sendBroadcast(new Intent(BleConstant.UNLOCK));
            long oldServiceTime = (long) get(ActivityGuanLiKey.this, null, SPContants.oldServiceTime, 0l);
            long oldPhoneTime = (long) get(ActivityGuanLiKey.this, null, SPContants.oldPhoneTime, 0l);
            long times = System.currentTimeMillis()-oldPhoneTime+oldServiceTime;
            if (error == Error.SUCCESS) {

                //toast("操作日志:" + records);
                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS, records);
                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS_LOCKID, lockid);
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid)){
                    userPresenter.uploadHistoryOfUnlock(get(ActivityGuanLiKey.this, null, SPContants.USER_ID, "") + "", lockid, records, "1",times/1000,extendedBluetoothDevice.getBatteryCapacity());//上传开锁记录
                }else {
                    userPresenter.uploadHistoryOfUnlock(sid, lockid, records, "1",times/1000,extendedBluetoothDevice.getBatteryCapacity());//上传开锁记录
                }

                if (extendedBluetoothDevice.getBatteryCapacity() <= 20) {
                    userPresenter.updateDianLiang(get(ActivityGuanLiKey.this, null, SPContants.USER_ID, "") + "", lockid, String.valueOf(extendedBluetoothDevice.getBatteryCapacity()));//低电量
                }

            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSearchDeviceFeature(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {
            Log.d("====iccard=","onSearchDeviceFeature"+i+"=="+i1);


        }


        @Override
        public void onModifyICCardPeriod(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, long l1, long l2, Error error) {

            Log.d("====iccard=","onModifyICCardPeriod");
            if (error==Error.SUCCESS){
                //同步校验锁时间
                cardno=l;
                long oldServiceTime = (long) get(ActivityGuanLiKey.this, null, SPContants.oldServiceTime, 0l);
                long oldPhoneTime = (long) get(ActivityGuanLiKey.this, null, SPContants.oldPhoneTime, 0l);
                long times = System.currentTimeMillis()-oldPhoneTime+oldServiceTime;
                mTTLockAPI.setLockTime(extendedBluetoothDevice,
                        0,
                        localKey.getLockVersion(),
                        localKey.getUnlockKey(),
                        times,
                        localKey.getLockFlagPos(),
                        localKey.getAesKeystr(),
                        localKey.getTimezoneRawOffset());
            }
        }

        @Override
        public void onDeleteICCard(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, Error error) {
            Log.d("====iccarddelete=","error=="+error);

            if (error==Error.SUCCESS){
                userPresenter.deleteIcCard(uid,ActivityICCardList.localKey.getLockId(),ActivityICCardList.cardId);
            }
        }

        @Override
        public void onClearICCard(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {
            Log.d("====iccard=","onClearICCard");

            if (error==Error.SUCCESS){
                userPresenter.clearIcCardList(uid,ActivityICCardList.localKey.getLockId());
            }
        }

        @Override
        public void onSetWristbandKeyToLock(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onSetWristbandKeyToDev(Error error) {

        }

        @Override
        public void onSetWristbandKeyRssi(Error error) {

        }


        @Override
        public void onFingerPrintCollection(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onModifyFingerPrintPeriod(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, long l1, long l2, Error error) {

        }

        @Override
        public void onDeleteFingerPrint(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, Error error) {

        }

        @Override
        public void onClearFingerPrint(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onSearchAutoLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, int i2, int i3, Error error) {
            Log.d("====iccard=","onSearchDeviceFeature");
        }

        @Override
        public void onModifyAutoLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {

        }

        @Override
        public void onReadDeviceInfo(ExtendedBluetoothDevice extendedBluetoothDevice, String s, String s1, String s2, String s3, String s4) {

        }

        @Override
        public void onEnterDFUMode(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {

        }

        @Override
        public void onSearchBicycleStatus(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {
            Log.d("====iccard=","onSearchDeviceFeature");
        }

        @Override
        public void onLock(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, int i2, long l, Error error) {
            Log.d("====iccard=","onLock==自动关锁");
        }

        @Override
        public void onScreenPasscodeOperate(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {

        }

        @Override
        public void onAddICCard(ExtendedBluetoothDevice extendedBluetoothDevice, int status, int i, long l, Error error) {
            Log.d("====onAddICCard=",status+"===="+i+"==="+l+"error=="+error.toString());
            operateSuccess=true;
            if (error==error.SUCCESS&&status==2){//添加ic卡成功
                //修改时间的ic
                if (!ActivityAddICCard.endDate.equals("")){ //选择了时间
                    mTTLockAPI.modifyICPeriod(extendedBluetoothDevice,0,ActivityAddICCard.localKey.getLockVersion(),
                            ActivityAddICCard.localKey.getAdminPs(),ActivityAddICCard.localKey.getUnlockKey(),
                            ActivityAddICCard.localKey.getLockFlagPos(),l,
                            Long.parseLong(ActivityAddICCard.startDate)*1000,
                            Long.parseLong(ActivityAddICCard.endDate)*1000,
                            ActivityAddICCard.localKey.getAesKeystr(),ActivityAddICCard.localKey.getTimezoneRawOffset());
                }else {
                    userPresenter.addIcCard(uid,ActivityAddICCard.localKey.getLockId(),l+"",ActivityAddICCard.icCardName,ActivityAddICCard.startDate,ActivityAddICCard.endDate);
                    ActivityGuanLiKey.this.sendBroadcast(new Intent(BleConstant.ADD_ICCARD));
                }
            }
//            mTTLockAPI.searchICCardNumber(extendedBluetoothDevice,0,ActivityAddICCard.localKey.getLockVersion(),
//                    ActivityAddICCard.localKey.getAdminPs(),
//                    ActivityAddICCard.localKey.getUnlockKey(),
//                    ActivityAddICCard.localKey.getLockFlagPos(),
//                    ActivityAddICCard.localKey.getAesKeystr());
//            mTTLockAPI.connect(extendedBluetoothDevice);


        }

        @Override
        public void onAddFingerPrint(ExtendedBluetoothDevice extendedBluetoothDevice, int status, int i, long l, Error error) {

        }

        @Override
        public void onRecoveryData(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

    };


    private void toRefreshData() {
        String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
        isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);

        if ("".equals(sid)){
            keyPresenter.myKey(uid, "",isLock);
        }else {
            keyPresenter.myKey(sid, "",isLock);
        }

    }
}
